<template>
  <div class="classify-container">
    <sticky class-name="sub-navbar ">
      <el-button
        style="margin-left: 10px;"
        type="success"
        @click="submitForm"
      >
        确定
      </el-button>
      <el-button
        type="warning"
        @click="draftForm"
      >
        取消
      </el-button>
    </sticky>
    <div class="casc-center">
      <el-cascader
        :options="list"
        v-model="value"
        @change="handleChange"
        placeholder="请选择分类"
        :props="{ checkStrictly: true,expandTrigger:'hover',value:'id' ,label:'label'}"
        clearable
      ></el-cascader>
    </div>

  </div>
</template>
<script>
import Sticky from "@/components/Sticky"; // 粘性header组件
import { getTreeData } from "@/utils/tree";
import api from "@/api/index";

export default {
  components: { Sticky },
  props: ["id", "toid"],
  mounted() {
    this.getData();
  },
  data() {
    return {
      list: [],
      cids: [],
      value: [],
      params: {
        platform: 0
      }
    };
  },
  methods: {
    getData() {
      api["categoryIndex"](this.params).then(res => {
        this.list = getTreeData(res.result);
        if (this.toid) {
          this.value = this.toid.split(",");

          this.value = this.value.map(val => {
            val = parseInt(val);
            return val;
          });
        } else {
          this.value = [];
        }
        console.log(this.value);
      });
    },
    draftForm() {
      this.$emit("on-close");
    },
    handleChange(e) {
      this.cids = e;
      var txt = e[e.length - 1];
    },
    submitForm() {
      var ids = this.cids.join(",");
      var cid = ids;
      var ctitle = "";
      this.cids.forEach(val => {
        ctitle = getsun(this.list, val);
      });

      function getsun(list, id) {
        console.log(list);
        console.log(id);

        var result = null;
        list.forEach(i => {
          console.log(i);
          if (i.id == id) {
            result = i.label;
          }
          if (i.children && !result) {
            result = getsun(i.children, id);
          }
        });

        return result;
      }
      if (cid.length < 1) {
        this.$emit("on-close");

        return;
      }
      var data = {
        id: this.id,
        cid,
        ctitle
      };

      this.$emit("on-ok", data);
      this.$emit("on-close");
    }
  }
};
</script>
<style lang="scss" scoped>
.classify-container {
  width: 100%;
  height: 100vh;
}
.casc-center {
  display: flex;
  padding-top: 100px;
  justify-content: center;
}
</style>
